<template>
  <div
    class="edit"
    contenteditable
    @keydown="changeTxt"
    style="width: 300px;height: 100px;border: 1px solid #ccc;text-align:left;"
  ></div>
</template>

<script>
let emjoyReg = /<img src=['"].*?img-code=['"](.*?)['"][^>]*?>/i;
export default {
  name: "editable-div",
  props: ["value"],
  data() {
    return {
      txt: ""
    };
  },
  methods: {
    changeTxt() {
      let _t = this.$el.innerHTML
      let match = _t.match(emjoyReg)
      while(match) {
        _t = _t.replace(match[0], `[${match[1]}]`);
        match = _t.match(emjoyReg)
      }
      this.txt = _t;
      this.$emit("input", this.txt)
    },
    insertText(obj) {
      var divEl = this.$el;
      this.$el.focus()
			var range, node;

			if (document.selection && document.selection.createRange) {
				divEl.focus();
				document.selection.createRange().pasteHTML(obj.img);
				divEl.focus();
      } else 
      if (window.getSelection && window.getSelection().getRangeAt) {
				range = window.getSelection().getRangeAt(0);
        range.collapse(false);
				node = range.createContextualFragment(obj.img);
				var c = node.lastChild;
				range.insertNode(node);
				if (c) {
					range.setEndAfter(c);
					range.setStartAfter(c)
				}
				var j = window.getSelection();
				j.removeAllRanges();
				j.addRange(range);
				divEl.focus();
      }
      this.changeTxt()
		},
  }
};
</script>

